package com.uetoken.cn.activity;

import android.content.Intent;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.ips.wcpaysdk.IpsPayUtil;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.uetoken.cn.R;
import com.uetoken.cn.adapter.RechargeAdapter;
import com.uetoken.cn.base.BaseActivity;
import com.uetoken.cn.bean.PurseInfoBean;
import com.uetoken.cn.bean.PurseListBean;
import com.uetoken.cn.bean.RechargeNum;
import com.uetoken.cn.common.ApiHelper;
import com.uetoken.cn.common.Constant;
import com.uetoken.cn.network.OkHttpUtils;
import com.uetoken.cn.network.Params;
import com.uetoken.cn.network.WebResponse;
import com.uetoken.cn.utils.AppUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class ExchangeActivity extends BaseActivity implements WebResponse {

    @BindView(R.id.topbar_back)
    ImageView topbarBack;
    @BindView(R.id.topbar_text)
    TextView topbarText;
    @BindView(R.id.topbar_text_sub)
    TextView topbarTextSub;
    @BindView(R.id.topbarLayout)
    RelativeLayout topbarLayout;
    @BindView(R.id.balanceTv)
    TextView balanceTv;
    @BindView(R.id.balanceUnitTv)
    TextView balanceUnitTv;
    @BindView(R.id.topLayout)
    RelativeLayout topLayout;
    @BindView(R.id.edt_activity_business_recharge_number)
    EditText mEdtRechargeNum;
    @BindView(R.id.rechargeAmountLayout)
    LinearLayout rechargeAmountLayout;
    @BindView(R.id.otherSelectionLayout)
    TextView otherSelectionLayout;
    @BindView(R.id.otherLayout)
    LinearLayout otherLayout;
    @BindView(R.id.ry_activity_business_recharge_number)
    RecyclerView mRyRechargeNum;
    @BindView(R.id.paymentMethodTv)
    TextView paymentMethodTv;
    @BindView(R.id.wechatIconIv)
    ImageView wechatIconIv;
    @BindView(R.id.wechatPayIv)
    ImageView wechatPayIv;
    @BindView(R.id.wechatLayout)
    RelativeLayout wechatLayout;
    @BindView(R.id.alipayIconIv)
    ImageView alipayIconIv;
    @BindView(R.id.alipayPayIv)
    ImageView alipayPayIv;
    @BindView(R.id.DCEPPayIv)
    ImageView DCEPPayIv;
    @BindView(R.id.alipayLayout)
    RelativeLayout alipayLayout;
    @BindView(R.id.totalAmountTv)
    TextView mQbConfirmPay;
    @BindView(R.id.confirmPayTv)
    TextView confirmPayTv;

    /**
     * 获取钱包历史网络请求码
     */
    private static final int NETWORK_REQUEST_CHARGE_CNV = 10;
    /**
     * 获取钱包金额网络请求码
     */
    private static final int NETWORK_REQUEST_GET_PURSE = 11;
    /**
     * 子钱包余额
     */
    private String balance;
    /**
     * 单位
     */
    private String purseName;
    /**
     * 子钱包id
     */
    private String purseId;
    private String nodeid;
    private String amount;
    private String balanceformat;
    private String purseunitname;
    private List<RechargeNum> mRechargeNums = new ArrayList<>();
    private RechargeAdapter mRechargeAdapter;
    //    private String rmbUnit = "元";
    private String cnvUnit = "CNV";
    private int payMethods = 1;//0:DCEP支付；1:微信支付；2:支付宝支付;
    private PurseListBean.DataBean mDataBean;
    private int pursetypeid;

    @Override
    public int getLayoutId() {
        return R.layout.activity_recharge;
    }

    @Override
    public void initView() {
        // 沉浸式状态栏
        QMUIStatusBarHelper.translucent(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            QMUIStatusBarHelper.setStatusBarLightMode(this);
        }
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        Intent intent = getIntent();
        mDataBean = (PurseListBean.DataBean) intent.getSerializableExtra("assetsDetailModel");
        purseId = mDataBean.getPurseid() + "";
        balance = mDataBean.getBalance() + "";
        purseName = mDataBean.getPursename();
        balanceformat = mDataBean.getBalanceformat();
        purseunitname = mDataBean.getPurseunitname();
        pursetypeid = mDataBean.getPursetypeid();
        nodeid = SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).getString(Constant.SP_NODE_ID, "");
        initRecyclerview();
        balanceTv.setText(balance);
        balanceUnitTv.setText(String.format(getString(R.string.str_account_balance), purseunitname));
        DCEPPayIv.setImageDrawable(ContextCompat.getDrawable(ExchangeActivity.this, R.mipmap.ic_select_nor));
        wechatPayIv.setImageDrawable(ContextCompat.getDrawable(ExchangeActivity.this, R.mipmap.ic_select_sel));
        alipayPayIv.setImageDrawable(ContextCompat.getDrawable(ExchangeActivity.this, R.mipmap.ic_select_nor));
    }

    @Override
    public void init() {

    }

    private void initRecyclerview() {
        for (int i = 0; i < 6; i++) {
            RechargeNum rechargeNum = new RechargeNum();
            //默认档次以1000，5000，10000，20000，50000，100000
            switch (i) {
                case 0:
                    rechargeNum.setSelect(true);
                    rechargeNum.setCNV(1000);
                    rechargeNum.setRMB(1000);
                    break;
                case 1:
                    rechargeNum.setSelect(false);
                    rechargeNum.setCNV(5000);
                    rechargeNum.setRMB(5000);
                    break;
                case 2:
                    rechargeNum.setSelect(false);
                    rechargeNum.setCNV(10000);
                    rechargeNum.setRMB(10000);
                    break;
                case 3:
                    rechargeNum.setSelect(false);
                    rechargeNum.setCNV(20000);
                    rechargeNum.setRMB(20000);
                    break;
                case 4:
                    rechargeNum.setSelect(false);
                    rechargeNum.setCNV(50000);
                    rechargeNum.setRMB(50000);
                    break;
                case 5:
                    rechargeNum.setSelect(false);
                    rechargeNum.setCNV(100000);
                    rechargeNum.setRMB(100000);
                    break;
            }
            mRechargeNums.add(rechargeNum);
        }

        mRyRechargeNum.setLayoutManager(new GridLayoutManager(this, 3));
        mRechargeAdapter = new RechargeAdapter(R.layout.item_recharge_num, mRechargeNums);
        mRyRechargeNum.setAdapter(mRechargeAdapter);

        mEdtRechargeNum.setText(mRechargeNums.get(0).getCNV() + "");
        mEdtRechargeNum.setSelection(mEdtRechargeNum.getText().toString().length());
        mQbConfirmPay.setText(String.format(getString(R.string.str_pay_total_amount), mRechargeNums.get(0).getCNV() + cnvUnit, mRechargeNums.get(0).getRMB() + ""));

        mRechargeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                mEdtRechargeNum.setText(mRechargeNums.get(position).getCNV() + "");
                mEdtRechargeNum.setSelection(mEdtRechargeNum.getText().toString().length());
                mQbConfirmPay.setText(String.format(getString(R.string.str_pay_total_amount), mRechargeNums.get(position).getCNV() + cnvUnit, mRechargeNums.get(position).getRMB() + ""));
                for (int i = 0; i < mRechargeNums.size(); i++) {
                    if (i == position) {
                        mRechargeNums.get(i).setSelect(true);
                    } else {
                        mRechargeNums.get(i).setSelect(false);
                    }
                }
                mRechargeAdapter.notifyDataSetChanged();
            }
        });

        mEdtRechargeNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                for (int i = 0; i < mRechargeNums.size(); i++) {
                    mRechargeNums.get(i).setSelect(false);
                }
                mRechargeAdapter.notifyDataSetChanged();
                String nums;
                if (TextUtils.isEmpty(s)) {
                    nums = "0";
                    confirmPayTv.setClickable(false);
                    confirmPayTv.setBackground(ContextCompat.getDrawable(ExchangeActivity.this, R.drawable.recharge_gray_shape));
                } else {
                    nums = s.toString();
                    confirmPayTv.setClickable(true);
                    confirmPayTv.setBackground(ContextCompat.getDrawable(ExchangeActivity.this, R.drawable.recharge_blue_shape));
                }
                mQbConfirmPay.setText(String.format(getString(R.string.str_pay_total_amount), nums + cnvUnit, nums + ""));
            }

            @Override
            public void afterTextChanged(Editable s) {
                String nums = s.toString();
                if (TextUtils.isEmpty(nums)) {
                    nums = "0";
                }
                mQbConfirmPay.setText(String.format(getString(R.string.str_pay_total_amount), nums + cnvUnit, nums + ""));
            }
        });
    }

    @Override
    public void onSuccessResponse(Call call, String response, int requestCode) throws IOException {
        LogUtils.dTag("onSuccessResponse==", "onSuccessResponse== response = " + response + " requestCode = " + requestCode);
        dissmissDialog();
        switch (requestCode) {
            case NETWORK_REQUEST_CHARGE_CNV:
                try {
                    JSONObject res = new JSONObject(response);

                    int result = res.getInt("result");
                    String message = res.getString("message");
                    if (result > 0) {
                        JSONObject data = new JSONObject(res.getString("data"));
                        Log.d("onSuccessResponse==", "Response->>payInfo->" + data);
                        if (AppUtils.isWxAppInstalled(getApplicationContext())) {
                            IpsPayUtil.startPay(data.toString(), ExchangeActivity.this);
                        }
                    } else {
                        ToastUtils.showShort(message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case NETWORK_REQUEST_GET_PURSE:
                PurseInfoBean mPurseInfoBean = new Gson().fromJson(response, PurseInfoBean.class);
                if (mPurseInfoBean.getResult() > 0) {
                    PurseInfoBean.DataBean mPurseData = mPurseInfoBean.getData();
                    if (mPurseData != null) {
                        balance = mPurseData.getBalance().toString();
                        LogUtils.dTag("onSuccessResponse==", "onSuccessResponse== balance = " + balance);
                        balanceTv.setText(mPurseData.getBalance());
                    }
                } else {
                    ToastUtils.showShort(mPurseInfoBean.getMessage());
                }
                break;
        }
    }

    @Override
    public void onFailResponse(Call call, IOException e, int requestCode) {
        dissmissDialog();
    }

    @OnClick({R.id.topbar_back, R.id.topbar_text_sub, R.id.confirmPayTv, R.id.wechatPayIv, R.id.alipayPayIv, R.id.DCEPPayIv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.topbar_back:
                finish();
                break;
            case R.id.topbar_text_sub:
                Intent intent = new Intent(ExchangeActivity.this, HistoryActivity.class);
                intent.putExtra("purseId", purseId);
                intent.putExtra("historyType", Constant.CHARGE_CNV_HIS);
                intent.putExtra("pursetypeid", pursetypeid);
                startActivity(intent);
                break;
            case R.id.confirmPayTv:
                amount = mEdtRechargeNum.getText() + "";
                getRechargePay(payMethods, amount);
                break;
            case R.id.DCEPPayIv:
                payMethods = 0;
                payMethods();
                ToastUtils.showLong(R.string.str_in_development);
                break;
            case R.id.wechatPayIv:
                payMethods = 1;
                payMethods();
                break;
            case R.id.alipayPayIv:
                payMethods = 2;
                payMethods();
                ToastUtils.showLong(R.string.str_in_development);
                break;

        }
    }

    private void payMethods() {
        if (payMethods == 0) {//DCEP
            DCEPPayIv.setImageDrawable(ContextCompat.getDrawable(ExchangeActivity.this, R.mipmap.ic_select_sel));
            wechatPayIv.setImageDrawable(ContextCompat.getDrawable(ExchangeActivity.this, R.mipmap.ic_select_nor));
            alipayPayIv.setImageDrawable(ContextCompat.getDrawable(ExchangeActivity.this, R.mipmap.ic_select_nor));
        } else if (payMethods == 1) {//微信
            DCEPPayIv.setImageDrawable(ContextCompat.getDrawable(ExchangeActivity.this, R.mipmap.ic_select_nor));
            wechatPayIv.setImageDrawable(ContextCompat.getDrawable(ExchangeActivity.this, R.mipmap.ic_select_sel));
            alipayPayIv.setImageDrawable(ContextCompat.getDrawable(ExchangeActivity.this, R.mipmap.ic_select_nor));
        } else if (payMethods == 2) {//支付宝
            DCEPPayIv.setImageDrawable(ContextCompat.getDrawable(ExchangeActivity.this, R.mipmap.ic_select_nor));
            wechatPayIv.setImageDrawable(ContextCompat.getDrawable(ExchangeActivity.this, R.mipmap.ic_select_nor));
            alipayPayIv.setImageDrawable(ContextCompat.getDrawable(ExchangeActivity.this, R.mipmap.ic_select_sel));
        } else {
            DCEPPayIv.setImageDrawable(ContextCompat.getDrawable(ExchangeActivity.this, R.mipmap.ic_select_sel));
            wechatPayIv.setImageDrawable(ContextCompat.getDrawable(ExchangeActivity.this, R.mipmap.ic_select_nor));
            alipayPayIv.setImageDrawable(ContextCompat.getDrawable(ExchangeActivity.this, R.mipmap.ic_select_nor));
        }
    }

    private void getRechargePay(int payMethods, String amount) {
        if (payMethods == 0) {//DCEP
            ToastUtils.showLong(R.string.str_in_development);
        } else if (payMethods == 1) {//微信
            getWechatPay(amount);
        } else if (payMethods == 2) {//支付宝
            ToastUtils.showLong(R.string.str_in_development);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        getPurse();
    }

    private void getWechatPay(String amount) {
        showLoading();
        OkHttpUtils.getInstance().getStringWithParam(this, ApiHelper.getChargeCNVUrl(), NETWORK_REQUEST_CHARGE_CNV,
                Params.getChargeCNVParams(nodeid, 0, amount));
    }

    private void getPurse() {
        showLoading();
        OkHttpUtils.getInstance().getStringWithParam(this, ApiHelper.getPurseUrl(), NETWORK_REQUEST_GET_PURSE,
                Params.getPurseParams(purseId));
    }
}
